<?php

require_once( 'HTTP_Advanced/http.inc' );
require_once( 'team2league.inc.php' );

#define('HT_DEFAULT', 'www.hattrick.org');
define('HT_DEFAULT', '193.34.189.84');
define('HT_PARAMS', '?outputType=XML');
define('HT_START', '/Common/menu.asp');
define('HT_HOME', '/Common/default.asp');
define('HT_MATCH', '/Common/matchDetails.asp');
define('HT_MATCHLINEUP', '/Common/matchLineup.asp');
define('HT_TEAM', '/Common/teamDetails.asp');
define('HT_CLUB', '/Common/club.asp');
define('HT_ECONOMY', '/Common/economy.asp');
define('HT_PLAYERS', '/Common/players.asp');
define('HT_REGION', '/Common/regionDetails.asp');
define('HT_WORLD', '/Common/chppxml.axd');
define('HT_TRAINING', '/Common/training.asp');
define('HT_SERIES', '/Common/leagueDetails.asp');
define('HT_TRANSFERS', '/Common/transferHistory.asp');
define('HT_MATCHES', '/Common/matches.asp');
#define('HT_MATCHESARCHIVE', '/Common/matchesArchive.asp');
define('HT_MATCHESARCHIVE', '/Common/chppxml.axd');
define('HT_LIVE', '/Common/live.asp');
define('HT_ALLIANCEDETAILS', '/Common/allianceDetails.asp');

define('TLEN_STAMINA', 1);
define('TLEN_KEEPER', 5);
define('TLEN_PLAYMAKER', 7);
define('TLEN_SCORER', 7);
define('TLEN_PASSING', 5);
define('TLEN_WINGER', 5);
define('TLEN_DEFENDER', 8);
define('TLEN_SETPIECES', 2);

define('T_GENERAL', 0);
define('T_STAMINA', 1);
define('T_SETPIECES', 2);
define('T_DEFENDING', 3);
define('T_SCORING', 4);
define('T_WINGER', 5);
define('T_SHOOTING', 6);
define('T_SHORTPASSES', 7);
define('T_PLAYMAKER', 8);
define('T_GOALTENDING', 9);
define('T_THROUGHPASSES', 10);
define('T_DEFENSIVEPOSITIONS', 11);

class HT_Client {
	var $HTClient;

	function HT_Client($agent = false)
	{
		$this->HTClient = &new http( HTTP_V11, false, false, $agent);
#		$this->HTClient->set_request_header("Accept-Encoding", "gzip");
	}

	function GetActivePage() {
		$this->HTClient->host = HT_DEFAULT;
		$code = $this->HTClient->get("/Common/menu.asp?outputType=XML");
		if ($code != HTTP_STATUS_OK)
		return false;
		$response = $this->HTClient->get_response_body();
		$parser = xml_parser_create();
		xml_parse_into_struct($parser,$response,$vals,$index);
		xml_parser_free($parser);
		$RecommendedURL = str_replace( "http://", "", $vals[$index['RECOMMENDEDURL'][0]]['value'] );
		$this->HTClient->host = $RecommendedURL;
		return $RecommendedURL;
	}


	function Login($username, $password, $useragent) {
		$RecommendedURL = $this->GetActivePage();

		$form = array('outputType' => 'XML', 'actionType' => 'login', 'loginType' => 'CHPP', 'Loginname' => $username, 'readonlypassword' => $password, 'user-agent' => $useragent);
		$code = $this->HTClient->post( '/Common/default.asp', $form );

		if ($code != HTTP_STATUS_OK) {
			echo "Login failed due to problem with Hattrick!\n";
			return false;
		}

		$response = $this->HTClient->get_response_body();
		
#		echo "<!-- ";
#		var_dump( $this->HTClient->_response->cookies->cookies);
#		echo "-->";

		$parser = xml_parser_create();
		xml_parse_into_struct($parser,$response,$vals,$index);
		xml_parser_free($parser);
		#echo "\nLogged in to $RecommendedURL\n\n";
		return ($vals[$index['ACTIONSUCCESSFUL'][0]]['value'] == "True");
	}

	
	function Logout() {
		$form = array('outputType' => 'XML', 'actionType' => 'logout');
		$code = $this->HTClient->post('/Common/default.asp', $form, 'http://' . $this->HTClient->host . '/Common/default.asp' );

		if ($code != HTTP_STATUS_OK) return false;

		$response = $this->HTClient->get_response_body();

		$parser = xml_parser_create();
		xml_parse_into_struct($parser,$response,$vals,$index);
		xml_parser_free($parser);

		return ($vals[$index['ACTIONSUCCESSFUL'][0]]['value'] == "True");
	}

	function GetFixtures($seriesID, $season) {
		
	}

	function GetRegionInfo($regionID) {
        	$form = array('outputType' => 'XML', 'actionType' => 'view', 'regionID' => $regionID);
        	$code = $this->HTClient->post('/Common/regionDetails.asp', $form, 'http://' . $this->HTClient->host . '/Common/default.asp' );

		if ($code == 500) return 'err';
        	elseif ($code != 200) return 'miscerr';
        	$htxml = $this->HTClient->get_response_body();

        	$parser = xml_parser_create('UTF-8');
        	xml_parse_into_struct($parser,$htxml,$vals,$index);
        	xml_parser_free($parser);

		$retvals = array();

		$retvals['RegionID']		= $vals[$index['REGIONID'][0]]['value'];
		$retvals['FetchedDate']		= $vals[$index['FETCHEDDATE'][0]]['value'];
        	$retvals['WeatherID']		= $vals[$index['WEATHERID'][0]]['value'];
        	$retvals['TomorrowWeatherID']	= $vals[$index['TOMORROWWEATHERID'][0]]['value'];
        	$retvals['NumberOfUsers']	= $vals[$index['NUMBEROFUSERS'][0]]['value'];
        	$retvals['NumberOfOnline']	= $vals[$index['NUMBEROFONLINE'][0]]['value'];
        	$retvals['LeagueID']		= $vals[$index['LEAGUEID'][0]]['value'];
        	$retvals['LeagueName']		= $vals[$index['LEAGUENAME'][0]]['value'];
        	$retvals['RegionName']		= $vals[$index['REGIONNAME'][0]]['value'];
        	
        	return $retvals;
	}

	function GetLanguageInfo() {

		$uri = 'http://' . $this->HTClient->host . HT_WORLD . '?file=worldlanguages';
		$code = $this->HTClient->get($uri);

		if ($code != 200)
			return false;
	
		if ($code == 500) return 'err';
        	elseif ($code != 200) return 'miscerr';
        	$htxml = $this->HTClient->get_response_body();

		$parser = xml_parser_create('UTF-8');
		xml_parse_into_struct($parser,$htxml,$vals,$index);
		xml_parser_free($parser);
		
		$numlanguages = count($index['LANGUAGEID']);

		$languages = array();

		for ($i = 0; $i < $numlanguages; $i++) {
			$lang = array();

			$lang['LanguageID'] = $vals[$index['LANGUAGEID'][$i]]['value'];
			$lang['LanguageName'] = $vals[$index['LANGUAGENAME'][$i]]['value'];
			
			$languages[] = $lang;
		}
		return ($languages);
	}
	
	function GetWorldInfo($file = null) {
		if ($file != null && file_exists($file)) {
			echo "reading worldDetails from file $file";
			$htxml = file_get_contents($file);
		} else {
			$uri = 'http://' . $this->HTClient->host . HT_WORLD . '?file=worlddetails';
			$code = $this->HTClient->get($uri);
			if ($code != 200)
				return false;
		
			if ($code == 500) return 'err';
	        	elseif ($code != 200) return 'miscerr';
	        	$htxml = $this->HTClient->get_response_body();
		}
        	$parser = xml_parser_create('UTF-8');
        	xml_parse_into_struct($parser,$htxml,$vals,$index);
        	xml_parser_free($parser);
        	
        	$numleagues = count($index['LEAGUEID']);
        	
		$world = array();
        	
        	for ($i = 0; $i < $numleagues; $i++) {
        		$country = array();
        		
        		$country['LeagueID'] = $vals[$index['LEAGUEID'][$i]]['value'];
			$country['LeagueName'] = $vals[$index['LEAGUENAME'][$i]]['value'];
			$country['Season'] = $vals[$index['SEASON'][$i]]['value'];
			//leagues starting in global season 11 are reported 10 seasons early
			if ($country['LeagueID'] > 1 && $country['LeagueID'] < 9) {
				$country['Season'] -= 10;
			}
			//Danmark and Finland are strange too (started in 13), reported 12 early
			if ($country['LeagueID'] == 11 || $country['LeagueID'] == 12) {
				$country['Season'] -= 12;
			}
			//Al Kuwait was created one season but introduced only the 2nd
			if ($country['LeagueID'] == 127) {
				$country['Season'] -= 1;
			}
			$country['MatchRound'] = $vals[$index['MATCHROUND'][$i]]['value'];
			$country['ShortName'] = $vals[$index['SHORTNAME'][$i]]['value'];
			$country['Continent'] = $vals[$index['CONTINENT'][$i]]['value'];
			$country['ZoneName'] = $vals[$index['ZONENAME'][$i]]['value'];
			$country['EnglishName'] = $vals[$index['ENGLISHNAME'][$i]]['value'];
			$country['CurrencyName'] = $vals[$index['CURRENCYNAME'][$i]]['value'];
			$country['CurrencyRate'] = $vals[$index['CURRENCYRATE'][$i]]['value'];
			$country['CupID'] = $vals[$index['CUPID'][$i]]['value'];
			$country['CupName'] = $vals[$index['CUPNAME'][$i]]['value'];
			$country['ActiveUsers'] = $vals[$index['ACTIVEUSERS'][$i]]['value'];
			$country['WaitingUsers'] = $vals[$index['WAITINGUSERS'][$i]]['value'];
			$country['TrainingDate'] = $vals[$index['TRAININGDATE'][$i]]['value'];
			$country['EconomyDate'] = $vals[$index['ECONOMYDATE'][$i]]['value'];
			$country['CupMatchDate'] = $vals[$index['CUPMATCHDATE'][$i]]['value'];
			$country['SeriesMatchDate'] = $vals[$index['SERIESMATCHDATE'][$i]]['value'];
			$country['NumberOfLevels'] = $vals[$index['NUMBEROFLEVELS'][$i]]['value'];

		 	$world[] = $country;
        	}
        	
        	return $world;
	}
	
	function GetTrainingStats($leagueID) {
		$form = array('outputType' => 'XML', 'actionType' => 'stats', 'StatsLeagueID' => $leagueID);
        	$code = $this->HTClient->post('/Common/training.asp', $form, 'http://' . $this->HTClient->host . '/Common/default.asp' );

		if ($code == 500) return 'hterr';
        	elseif ($code != 200) return 'miscerr';
        	$htxml = $this->HTClient->get_response_body();

        	$parser = xml_parser_create('UTF-8');
        	xml_parse_into_struct($parser,$htxml,$vals,$index);
        	xml_parser_free($parser);

		$retvals = array();
		$zerotypes = 0;
		
		/*
		The training types that have no teams in a region training it are not included in the XML list.
		We use $zerotypes to counteract this.
		*/

		if ($vals[$index['TRAININGSTATLIST'][0]]['attributes']['COUNT'] > 13) { echo "new training type added!"; }

		for ($i = 0; $i <= 12; $i++) {
			$tn = 0;
			if ($vals[$index['TRAININGSTATLIST'][0]]['attributes']['COUNT'] > 0) {
				if ($vals[$index['TRAININGTYPE'][$i-$zerotypes]]['value'] == $i) {
					$tn = $vals[$index['NUMBEROFTEAMS'][$i-$zerotypes]]['value'];
				} else {
					$zerotypes++;
				}
			}
			$retvals[] = $tn;
		}
		
		/*
		
		0	General
		1	Stamina
		2	Set Pieces
		3	Defending
		4	Scoring
		5	Cross Pass (Winger)
		6	Shooting
		7	Short Passes
		8	Playmaking
		9	Goaltending
		10	Through passes
		11	Defensive positions
		12	Wing Attacks
		
		*/
		
        	return $retvals;
	}
	
	function getSeries($llu) {
		$form = array('outputType' => 'XML', 'actionType' => 'view', 'LeagueLevelUnitID' => $llu);
		$code = $this->HTClient->post('/Common/leagueDetails.asp', $form, 'http://' . $this->HTClient->host . '/Common/default.asp' );
		
		
		if ($code == 500) return 'hterr';
        	elseif ($code != 200) return 'miscerr';
        	$htxml = $this->HTClient->get_response_body();

        	$parser = xml_parser_create('UTF-8');
        	xml_parse_into_struct($parser,$htxml,$vals,$index);
        	xml_parser_free($parser);

		$retvals = array();
		$teamids = array();
		
		for ($i = 0; $i <= 7; $i++) {
			$teamids[] = $vals[$index['TEAMID'][$i]]['value'];
		}

		$retvals['teams'] = $teamids;
		$retvals['name'] = $vals[$index['LEAGUELEVELUNITNAME'][0]]['value'];
		$retvals['level'] = $vals[$index['LEAGUELEVEL'][0]]['value'];
		$retvals['leagueid'] = $vals[$index['LEAGUEID'][0]]['value'];
		return $retvals;
	}

	function getTeam($teamid, $paramisuserid = false) {
		if ($paramisuserid) $form = array('outputType' => 'XML', 'actionType' => 'view', 'userID' => $teamid);
		else $form = array('outputType' => 'XML', 'actionType' => 'view', 'teamID' => $teamid);
		$code = $this->HTClient->post('/Common/teamDetails.asp', $form, 'http://' . $this->HTClient->host . '/Common/default.asp' );
		
		if ($code == 500) return 'hterr';
        	elseif ($code != 200) return 'miscerr';
        	$htxml = $this->HTClient->get_response_body();

        	$parser = xml_parser_create('UTF-8');
        	xml_parse_into_struct($parser,$htxml,$vals,$index);
        	xml_parser_free($parser);

		$retvals = array();

		$retvals['fetcheddate']		= $vals[$index['FETCHEDDATE'][0]]['value'];

		$retvals['userid']		= $vals[$index['USERID'][1]]['value'];
		$retvals['teamid']		= $vals[$index['TEAMID'][0]]['value'];
		$retvals['languageid']		= $vals[$index['LANGUAGEID'][0]]['value'];
		$retvals['language']		= $vals[$index['LANGUAGE'][0]]['value'];
		if ($vals[$index['HASSUPPORTER'][0]]['value'] == "True") {
			$retvals['hassupporter'] = 1;
		} else {
			$retvals['hassupporter'] = 0;
		}
		$retvals['loginname']		= $vals[$index['LOGINNAME'][0]]['value'];
		$retvals['email']		= $vals[$index['EMAIL'][0]]['value'];
		$retvals['name']		= $vals[$index['NAME'][0]]['value'];
		$retvals['icq']			= $vals[$index['ICQ'][0]]['value'];
		$retvals['signupdate']		= $vals[$index['SIGNUPDATE'][0]]['value'];
		$retvals['activationdate']	= $vals[$index['ACTIVATIONDATE'][0]]['value'];
		$retvals['lastlogindate']	= $vals[$index['LASTLOGINDATE'][0]]['value'];

		$retvals['teamname']            = $vals[$index['TEAMNAME'][0]]['value'];
		$retvals['shortteamname']	= $vals[$index['SHORTTEAMNAME'][0]]['value'];
		$retvals['arenaid']		= $vals[$index['ARENAID'][0]]['value'];
		$retvals['leagueid']		= $vals[$index['LEAGUEID'][0]]['value'];
		$retvals['regionid']		= $vals[$index['REGIONID'][0]]['value'];
		$retvals['trainerid']		= $vals[$index['TRAINERID'][0]]['value'];
		if ($vals[$index['CUP'][0]]['attributes']['AVAILABLE'] == "true") {
			if ($vals[$index['STILLINCUP'][0]]['value'] === "true") {
				$retvals['stillincup'] = 1;
			} else {
				$retvals['stillincup'] = 0;
			}
		} else {
			$retvals['stillincup'] = -1;
		}
		
	
		if ($vals[$index['LEAGUELEVELUNIT'][0]]['attributes']['AVAILABLE'] == "true") $retvals['serieid'] = $vals[$index['LEAGUELEVELUNITID'][0]]['value'];
		
		return $retvals;
	}
	/**
	 * Retrieve matches archive for team $id, or for user's own team.
	 *
	 * @param    string   teamID
	 * @access   public
	 */
	function getMatchesArchiveXML($id = false, $cup = false, $first = false, $last = false, $season = false) {
		$form = array();
		$form['file'] = 'matchesarchive';
		$form['isYouth'] = 'false'; //this should be implemented as an option eventually
		if (!$cup)
			$form['actionType'] = 'view';
		else
			$form['actionType'] = 'viewCup';
		if ($id)
			$form['teamID'] = $id;
		if ($first)
			$form['FirstMatchDate'] = urlencode($first);
		if ($last)
			$form['LastMatchDate'] = urlencode($last);
		if ($season)
			$form['Season'] = $season;

		$uri = 'http://' . $this->HTClient->host . HT_MATCHESARCHIVE . '?';
		foreach ($form as $a => $k) {
			$uri .= "$a=$k&";
		}
		$code = $this->HTClient->get($uri);
		if ($code != 200)
			return false;
		return $this->HTClient->get_response_body();
	}
	
	/**
	 * Retrieve matches archive for team $id, or for user's own team.
	 *
	 * @param    string   teamID
	 * @access   public
	 */
	function getMatchesArchive($id = false, $cup = false, $first = false, $last = false, $season = false) {
		if ((! $id) && ($this->matchesArchive))
			return $this->matchesArchive;
#		echo "<!-- fetching matchesArchiveXML with vars: $id $cup $first $last $season -->\n";
		$xml = $this->getMatchesArchiveXML($id, $cup, $first, $last, $season);
#		echo "<!-- $xml -->\n";
		if ($xml) {
			$parser = xml_parser_create();
			xml_parse_into_struct($parser, $xml, $vals, $index);
			xml_parser_free($parser);
			if (! $vals[$index['FILENAME'][0]]['value'])
				return false;
			for ($i = 0; $i < count($index['MATCHID']); $i++) {
				$match[$i] = array(
					'MATCHID' => $vals[$index['MATCHID'][$i]]['value'],
					'HOMETEAMID' => $vals[$index['HOMETEAMID'][$i]]['value'],
					'HOMETEAMNAME' => $vals[$index['HOMETEAMNAME'][$i]]['value'],
					'AWAYTEAMID' => $vals[$index['AWAYTEAMID'][$i]]['value'],
					'AWAYTEAMNAME' => $vals[$index['AWAYTEAMNAME'][$i]]['value'],
					'MATCHDATE' => $vals[$index['MATCHDATE'][$i]]['value'],
					'MATCHTYPE' => $vals[$index['MATCHTYPE'][$i]]['value'],
					'HOMEGOALS' => $vals[$index['HOMEGOALS'][$i]]['value'],
					'AWAYGOALS' => $vals[$index['AWAYGOALS'][$i]]['value']
				);
			}
			$this->matchesArchive = array(
				'FILENAME' => $vals[$index['FILENAME'][0]]['value'],
				'VERSION' => $vals[$index['VERSION'][0]]['value'],
				'USERID' => $vals[$index['USERID'][0]]['value'],
				'FETCHEDDATE' => $vals[$index['FETCHEDDATE'][0]]['value'],
				'TEAMID' => $vals[$index['TEAMID'][0]]['value'],
				'TEAMNAME' => $vals[$index['TEAMNAME'][0]]['value'],
				'FIRSTMATCHDATE' => $vals[$index['FIRSTMATCHDATE'][0]]['value'],
				'LASTMATCHDATE' => $vals[$index['LASTMATCHDATE'][0]]['value'],
				'MATCH' => $match
			);
			return $this->matchesArchive;
		}
		else return false;
	}

	/**
	 * Get the home and away flags for team $id, or for user's own team.
	 *
	 * @param	string	teamID
	 * @access	public
	 */
	function getFlags($id = false, $fromdate = false) {
		$teamdetails = $this->getTeam($id);
		if (!$fromdate) $fromdate = $teamdetails['activationdate'];
		$todate = strftime("%Y-%m-%d", strtotime($fromdate) + (8 * 7 * 86400));
		$ownleague = $teamdetails['leagueid'];
		$ownid = $teamdetails['teamid'];
		$matchesfetched = 0;
		$flags = array("home"=>array(), "away"=>array(), "info"=>$teamdetails);
		do {
			$matchesarchive = $this->getMatchesArchive($ownid, false, $fromdate, $todate);
			$matchesfetched = count($matchesarchive['MATCH']);
			if ($matchesfetched == 0) return $flags;
			foreach ($matchesarchive['MATCH'] as $match) {
				if (	$match['MATCHTYPE'] == 4 ||
					$match['MATCHTYPE'] == 5 ||
					$match['MATCHTYPE'] == 8 ||
					$match['MATCHTYPE'] == 9 ||
					$match['MATCHTYPE'] == 12 ) {
					if ($match['HOMETEAMID'] == $ownid) {
						$flags['home'][teamid2leagueid($match['AWAYTEAMID'],$this)] = 1;
#						echo "<!-- home ";
#						echo teamid2leagueid($match['AWAYTEAMID'],$this);
#						echo ": {$match['MATCHID']} -->\n";
					} else if ($match['AWAYTEAMID'] == $ownid) {
						$flags['away'][teamid2leagueid($match['HOMETEAMID'],$this)] = 1;
#						echo "<!-- away ";
#						echo teamid2leagueid($match['HOMETEAMID'],$this);
#						echo ": {$match['MATCHID']} -->\n";
					}
				}
			}
			$fromdate = $matchesarchive['MATCH'][$matchesfetched-1]['MATCHDATE'];
			$todate = strftime("%Y-%m-%d", strtotime($fromdate) + (8 * 7 * 86400));
		} while ($matchesfetched > 1);
#		echo "<!-- stopped at $fromdate to $todate -->\n";
		return $flags;
	}
	
	function getAllianceDetailsXML($id, $action = "view", $subset = 0, $roleid = 0) {
        if ($id > 0)
                $form = array('outputType' => 'XML',
                        'actionType' => $action,
                        'allianceID' => $id,
			'subset' => $subset
                );
        $code = $this->HTClient->post(HT_ALLIANCEDETAILS, $form, 'http://'.$this->HTClient->host.HT_HOME);
        if ($code != 200)
                return false;
        return $this->HTClient->get_response_body();
	}

	function getAllianceDetails($id) {
		$xml = $this->getAllianceDetailsXML($id);
		if ($xml) {
			$parser = xml_parser_create();
			xml_parse_into_struct($parser, $xml, $vals, $index);
			xml_parser_free($parser);
			if (!isset($index['FILENAME'])) {
				echo "Fetch failed! Wrong username/password?<br />";
				return(false);
			}
			if ($vals[$index['CREATIONDATE'][0]]['value'] === "30-12-1899") {
				return("remove");
			}
			$retvals = array(
				'id' => $vals[$index['ALLIANCEID'][0]]['value'],
				'name' => $vals[$index['ALLIANCENAME'][0]]['value'],
				'nummembers' => $vals[$index['NUMBEROFMEMBERS'][0]]['value']
			);
			if(isset($index['LOGOURL'])) $retvals['logourl'] = $vals[$index['LOGOURL'][0]]['value'];
			if(isset($index['ABBREVIATION'])) $retvals['abbrev'] = $vals[$index['ABBREVIATION'][0]]['value'];
			return($retvals);
		} else {
			return(false);
		}
	}
	
	function getAllianceRoles($id) {
		$xml = $this->getAllianceDetailsXML($id, "roles");
		if ($xml) {
			$roles = array(); 
			$parser = xml_parser_create();
			xml_parse_into_struct($parser, $xml, $vals, $index);
			xml_parser_free($parser);
			if ((!$vals[$index['FILENAME'][0]]['value']) || (!isset($index['ROLES'])))
				return(false);
			for ($i = 0; $i < $vals[$index['ROLES'][0]]['attributes']['COUNT']; $i++) {
				$roles[] = array(
					'id' => $vals[$index['ROLEID'][$i]]['value'],
					'name' => $vals[$index['ROLENAME'][$i]]['value'],
					'rank' => $vals[$index['ROLERANK'][$i]]['value'],
					'membercount' => $vals[$index['ROLEMEMBERCOUNT'][$i]]['value']
				);
			}
			return($roles);
		} else return (false);
	}

	function getAllianceMembers($id) {
		$xml = $this->getAllianceDetailsXML($id, "members");
		if ($xml) {
			$members = $this->parseAllianceMembersXML($xml);
			if (!$members) return false;
			if (count($members) == 100) {
				$xml = $this->getAllianceDetailsXML($id, "membersSubset", 0);
				$members = $this->parseAllianceMembersXML($xml);
				if ($members != array() && !$members) return false;
				echo "downloaded members ";
				for ($i = 65; $i <= 90; $i++) {
					$xml = $this->getAllianceDetailsXML($id, "membersSubset", $i);
					$part = $this->parseAllianceMembersXML($xml);
					if ($part != array() && !$part) return false;
					echo chr($i) . "\n";
					flush(); ob_flush();
					$members = array_merge($members, $part);
				}
				echo "<br />";
				return($members);
			} else return($members);
		} else return(false);
	}

	function parseAllianceMembersXML($xml) {
		$members = array();
		$parser = xml_parser_create();
		xml_parse_into_struct($parser, $xml, $vals, $index);
		xml_parser_free($parser);
		if ((!$vals[$index['FILENAME'][0]]['value']) || (!isset($index['MEMBERS'])))
			return(false);
		for ($i = 0; $i < $vals[$index['MEMBERS'][0]]['attributes']['COUNT']; $i++) {
			$members[] = array(
				'userid' => $vals[$index['USERID'][$i+1]]['value'],
				'roleid' => $vals[$index['ROLEID'][$i]]['value'],
				'member' => $vals[$index['MEMBERSHIPDATE'][$i]]['value']
			);
		}
		return($members);
	}
}

?>
